package com.jxtc.enterprise.common.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.jxtc.enterprise.common.utils.Result;
import com.jxtc.enterprise.common.utils.ResultGenerator;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * 向阿里云 oss 对象存储空间上传文件（主要是图片）的 接口实现类
 */
@Slf4j
@RestController
@RequestMapping("/jxtc/enterprise/oss")
public class JxOssController {
    private String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    private String accessKeyId = "LTAI5t73gzGH975QGrhBpUqK";
    private String accessKeySecret = "Kyt6Pc6UN3IfBxkXgC6R2X0OsB1dLh";
    private String bucketName = "yong-shan-tuan";

    @ApiResponse(responseCode = "200", description = "code 为 200 时， 表示上传图片成功，此时 data 字段为图片在对象存储服务中的 url")
    @Operation(summary = "12.1 上传图片到对象存储服务，并返回图片链接", tags = {"12. OSS 对象存储"}, operationId = "12.1")
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result<String> upload(@RequestParam("file") MultipartFile multipartFile) {
        log.info("文件上传，文件名：{}", multipartFile.getOriginalFilename());
        // 调用阿里云oss进行文件类上传
        String url = null;

        try {
            url = uploadFile(multipartFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        log.info("文件上传完成，路径为：{}", url);

        return ResultGenerator.genSuccessResult(url, "success");
    }

    /**
     * 实现上传图片到OSS
     */
    public String uploadFile(MultipartFile file) throws IOException {
        // 获取上传的文件的输入流
        InputStream inputStream = file.getInputStream();

        // 避免文件覆盖
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        //上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, fileName, inputStream);

        //文件访问路径
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;
        // 关闭ossClient
        ossClient.shutdown();
        return url;// 把上传到oss的路径返回
    }

}
